import mqtt from './mqtt.min.js';

let client = null;
var fangfa = function() {}

function initMqtt(user, no) {
	if (client == null) {
		let timestamp = Date.parse(new Date());
		var options = {
			wsOptions: {},
			protocolVersion: 4, //MQTT连接协议版本
			clientId: "myclientid_" + timestamp,
			keepalive: 60,
			clean: false,
			username: 'admin',
			password: 'admin',
			reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
			connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
			resubscribe: true //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
		};
		var hosts = 'wxs:gjwy.nephil.cn:15679/ws'
		client = mqtt.connect(hosts, options);
		client.on('connect', () => {
			console.log("连接成功", user)
			if (!!user) {
				client.subscribe(user, {
					qos: 1
				})
				console.log("订阅成功", user)
			}
		});
		// 接收消息推送
		client.on('message', (topic, message) => {
			fangfa(topic, message.toString())
		});
	} else {
		if (!!user) {
			client.subscribe(user, {
				qos: 1
			})
			console.log("订阅成功", user)
		}
	}
}

// 发送消息
function handleclick(user, msg) {
	client.publish(user, msg, error => {
		console.log(error, '发送成功', msg, user);
	});
}

// 取消订阅
function unsubscribeFn() {

}

// 配置接收信息的函数
function onMessageArrived(val) {
	try {
		fangfa = val
	} catch (err) {
		console.log(err);
	}
}

export {
	initMqtt,
	handleclick,
	onMessageArrived
};
